package com.mck.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mck.entity.AiRequest;
import com.mck.entity.AiResponse;
import com.mck.service.AiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AiServiceImpl implements AiService {

  @Value("${ai.model.api-key}")
  private String apiKey;

  @Value("${ai.model.base-url:https://api.deepseek.com}")
  private String baseUrl;

  @Value("${ai.model.name:deepseek-r1}")
  private String modelName;

  private final RestTemplate restTemplate;
  private final ObjectMapper objectMapper = new ObjectMapper();

  public AiServiceImpl() {
    // 创建一个可以多次读取响应的RestTemplate
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    // 大幅增加超时时间
    factory.setConnectTimeout(30000); // 30秒
    factory.setReadTimeout(120000); // 2分钟
    this.restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(factory));
  }

  @Override
  public AiResponse processAiRequest(AiRequest request) {
    int maxRetries = 3;
    int retryCount = 0;

    while (retryCount < maxRetries) {
      try {
        return callAiApi(request);
      } catch (Exception e) {
        retryCount++;

        // 如果是超时错误并且还有重试次数，则重试
        if (isTimeoutException(e) && retryCount < maxRetries) {
          System.out.println("API请求超时，正在进行第 " + retryCount + " 次重试...");
          try {
            // 指数退避策略，每次重试等待时间增加
            Thread.sleep(1000 * retryCount);
          } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
          }
        } else {
          // 其他错误或已达到最大重试次数
          System.err.println("AI处理请求时出错: " + e.getMessage());
          e.printStackTrace();
          return AiResponse.builder()
              .success(false)
              .errorMsg("AI处理请求时发生错误: " + e.getMessage())
              .build();
        }
      }
    }

    // 达到最大重试次数仍然失败
    return AiResponse.builder()
        .success(false)
        .errorMsg("AI服务暂时不可用，请稍后再试。")
        .build();
  }

  @Override
  public void processAiRequestStream(AiRequest request, SseEmitter emitter) {
    try {
      System.out.println("处理流式AI请求: " + request.getMessage());

      // 准备请求头
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_JSON);
      headers.setBearerAuth(apiKey);
      headers.add("Accept", "text/event-stream");

      // 准备消息
      List<Map<String, String>> messages = new ArrayList<>();

      // 系统消息
      Map<String, String> systemMessage = new HashMap<>();
      systemMessage.put("role", "system");
      systemMessage.put("content", "你是一个有帮助的AI助手。");
      messages.add(systemMessage);

      // 用户消息
      Map<String, String> userMessage = new HashMap<>();
      userMessage.put("role", "user");
      userMessage.put("content", request.getMessage());
      messages.add(userMessage);

      // 准备请求体
      Map<String, Object> requestBody = new HashMap<>();
      requestBody.put("model", "deepseek-chat"); // 使用正确的模型名称
      requestBody.put("messages", messages);
      requestBody.put("temperature", 0.7);
      requestBody.put("max_tokens", 2000);
      requestBody.put("stream", true); // 启用流式输出

      // 创建HTTP请求实体
      HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

      // 构建完整的API端点URL
      String endpoint = baseUrl + "/v1/chat/completions";

      // 发送请求并处理流式响应
      System.out.println("发送流式请求到DeepSeek API: " + endpoint);

      // 使用 RestTemplate 的 exchange 方法获取原始响应
      ResponseEntity<byte[]> responseEntity = restTemplate.exchange(
          endpoint,
          HttpMethod.POST,
          entity,
          byte[].class);

      // 处理流式响应
      if (responseEntity.getStatusCode().is2xxSuccessful() && responseEntity.getBody() != null) {
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(new java.io.ByteArrayInputStream(responseEntity.getBody())));

        String line;
        StringBuilder contentBuilder = new StringBuilder();

        while ((line = reader.readLine()) != null) {
          if (line.startsWith("data: ")) {
            String data = line.substring(6);

            // 跳过 [DONE] 消息
            if ("[DONE]".equals(data)) {
              continue;
            }

            try {
              // 使用 Jackson 直接解析 JSON 字符串
              Map<String, Object> jsonData = objectMapper.readValue(data, Map.class);

              if (jsonData != null && jsonData.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) jsonData.get("choices");
                if (!choices.isEmpty()) {
                  Map<String, Object> choice = choices.get(0);
                  Map<String, Object> delta = (Map<String, Object>) choice.get("delta");

                  if (delta != null && delta.containsKey("content")) {
                    String content = (String) delta.get("content");
                    contentBuilder.append(content);

                    // 发送部分内容到客户端
                    emitter.send(SseEmitter.event()
                        .name("message")
                        .data(content));
                  }
                }
              }
            } catch (Exception e) {
              System.err.println("解析流式响应时出错: " + e.getMessage());
              e.printStackTrace();
            }
          }
        }

        // 发送完整内容
        emitter.send(SseEmitter.event()
            .name("complete")
            .data(contentBuilder.toString()));
      }

    } catch (Exception e) {
      System.err.println("流式AI处理请求时出错: " + e.getMessage());
      e.printStackTrace();
      try {
        emitter.send(SseEmitter.event()
            .name("error")
            .data("AI处理请求时发生错误: " + e.getMessage()));
      } catch (IOException ex) {
        // 忽略发送错误消息时的异常
      }
    }
  }

  private boolean isTimeoutException(Exception e) {
    return (e instanceof ResourceAccessException && e.getCause() instanceof SocketTimeoutException) ||
        (e.getMessage() != null && e.getMessage().contains("timed out"));
  }

  private AiResponse callAiApi(AiRequest request) {
    System.out.println("处理AI请求: " + request.getMessage());

    // 准备请求头
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setBearerAuth(apiKey);

    // 添加可能需要的其他头信息
    headers.add("Accept", "application/json");

    // 准备消息
    List<Map<String, String>> messages = new ArrayList<>();

    // 系统消息
    Map<String, String> systemMessage = new HashMap<>();
    systemMessage.put("role", "system");
    systemMessage.put("content", "你是一个有帮助的AI助手。");
    messages.add(systemMessage);

    // 用户消息
    Map<String, String> userMessage = new HashMap<>();
    userMessage.put("role", "user");
    userMessage.put("content", request.getMessage());
    messages.add(userMessage);

    // 准备请求体
    Map<String, Object> requestBody = new HashMap<>();
    requestBody.put("model", "deepseek-chat"); // 使用正确的模型名称
    requestBody.put("messages", messages);

    // 添加可能需要的其他参数
    requestBody.put("temperature", 0.7);
    requestBody.put("max_tokens", 2000);
    // 尝试添加其他可能需要的参数
    requestBody.put("stream", false);

    // 创建HTTP请求实体
    HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

    // 构建完整的API端点URL
    String endpoint = baseUrl + "/v1/chat/completions";

    // 发送请求
    System.out.println("发送请求到DeepSeek API: " + endpoint);
    System.out.println("请求头: " + headers);
    System.out.println("请求体: " + requestBody);

    ResponseEntity<Map> response;
    try {
      response = restTemplate.postForEntity(endpoint, entity, Map.class);
    } catch (HttpClientErrorException e) {
      System.err.println("API错误状态码: " + e.getStatusCode());
      System.err.println("API错误响应: " + e.getResponseBodyAsString());

      // 尝试解析错误响应
      try {
        // 可以在这里解析错误响应JSON，获取更详细的错误信息
        System.err.println("错误详情: " + e.getResponseBodyAsString());
      } catch (Exception ex) {
        System.err.println("无法解析错误响应: " + ex.getMessage());
      }

      throw e;
    }

    // 解析响应
    Map<String, Object> responseBody = response.getBody();
    System.out.println("API响应: " + responseBody);

    String aiMessage = "";

    if (responseBody != null && responseBody.containsKey("choices")) {
      List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
      if (!choices.isEmpty()) {
        Map<String, Object> choice = choices.get(0);
        Map<String, Object> message = (Map<String, Object>) choice.get("message");
        aiMessage = (String) message.get("content");
      }
    }

    if (aiMessage.isEmpty()) {
      aiMessage = "AI无法生成回复。";
    }

    System.out.println("收到AI响应: " + aiMessage);

    return AiResponse.builder()
        .message(aiMessage)
        .success(true)
        .build();
  }
}
